package com.xiaoniu.udp;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import io.vertx.core.json.JsonObject;

import java.time.LocalDateTime;

/**
 * Created by sweet on 2018/1/2.
 * ---------------------------
 */
public class UdpClientVerticle extends AbstractVerticle {
    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new UdpClientVerticle());
    }

    @Override
    public void start() throws Exception {
        final DatagramSocket server = vertx.createDatagramSocket();

        vertx.eventBus().<String>consumer(this.getClass().getName()+"Sender", msg -> {

            System.out.println(msg.body());

            server.send(msg.body(), 8080, "127.0.0.1", res -> {
                if (res.succeeded()) {
                    msg.reply("OK");
                } else {
                    res.cause().printStackTrace();
                    msg.reply("ERROR");
                }
            });
        });

        server.listen(8081, "127.0.0.1", h -> {
            if (h.succeeded()) {
                DatagramSocket result = h.result();
                result.handler(socket -> {
                    String s = socket.data().toString();
                    System.out.println("Client 收到消息：" + s + "\n");
                    String host = socket.sender().host();
                    int port = socket.sender().port();
                    String path = socket.sender().path();
//                    System.out.println("host: " + host+", port: " + port + ", path: " + path);
                });
            } else {
                h.cause().printStackTrace();
            }
        });

        vertx.setPeriodic(10000l, r -> {
            vertx.eventBus().send(this.getClass().getName()+"Sender", "Hello world " + LocalDateTime.now(), h -> {
               if (h.succeeded()) {
                   System.out.println("client 发送 " + h.result().body().toString());
               } else {
                   h.cause().printStackTrace();
               }
            });
        });
    }
}
